﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;

namespace CommunityToolkitMvvmDemo.Behaviors
{
    /// <summary>
    /// 行为捕捉类
    /// NuGet 引用 项目 Microsoft.Xaml.Behaviors.Wpf
    /// </summary>
    public class TextValidationErrorBehavior : Behavior<FrameworkElement>
    {
        protected override void OnAttached()
        {
            // 事件监听
            this.AssociatedObject.AddHandler(Validation.ErrorEvent, 
                new EventHandler<ValidationErrorEventArgs>(OnValidationError));
        }

        private void OnValidationError(Object sender, ValidationErrorEventArgs e)
        {
            if (AssociatedObject.DataContext is ITextValidationError mainModel)
            {
                // 表示新产生的行为
                if (e.Action == ValidationErrorEventAction.Added)
                {
                    mainModel.Errors.Add(e.Error.ErrorContent.ToString());
                }
                else if (e.Action == ValidationErrorEventAction.Removed) // 该行为被移除，即代表验证通过
                {
                    mainModel.Errors.Remove(e.Error.ErrorContent.ToString());
                }
            }
        }

        protected override void OnDetaching()
        {
            // 移除事件监听
            this.AssociatedObject.RemoveHandler(Validation.ErrorEvent, new EventHandler<ValidationErrorEventArgs>(OnValidationError));
        }
    }

}
